package com.zoweunion.mechanic.controller.base;


import com.alibaba.fastjson.JSONObject;
import com.zoweunion.mechanic.controller.BaseController;
import com.zoweunion.mechanic.model.ResponseBean;
import com.zoweunion.mechanic.model.app.City;
import com.zoweunion.mechanic.model.app.Province;
import com.zoweunion.mechanic.model.app.Region;
import com.zoweunion.mechanic.service.app.AppService;
import com.zoweunion.mechanic.service.shangji.ShangJiService;
import com.zoweunion.mechanic.util.MyException;
import com.zoweunion.mechanic.util.constants.Constants;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/address")
public class AddressController extends BaseController {

    @Autowired
    private AppService appService;
    @Autowired
    private ShangJiService shangJiService;

    @PostMapping(value="/getAddress")
    public ResponseBean getAddress() {
        logBefore(logger, "查询全部");
        Map<String, Object> resMap=new HashMap<>();
        List<Map<String,Object>> provinceList=appService.provinceAll();
        List<Map<String,Object>> cityList=appService.cityAll();
        List<Map<String,Object>> areaList=appService.areaAll();
        resMap.put("provinceList",provinceList);
        resMap.put("cityList",cityList);
        resMap.put("areaList",areaList);
        logAfter(logger);
        return new ResponseBean(Constants.CODE_SUCCESS,"操作成功",resMap);
    }

    @PostMapping(value="/getProvince")
    public ResponseBean province(@RequestBody String str) {
        logBefore(logger, "查询省");
        Map<String, Object> result=new HashMap<>();
        Map<String, Object> reqMap = JSONObject.parseObject(str,Map.class);
        List<Map<String,Object>> addressList=appService.province(reqMap);
        if(null!=addressList&&addressList.size()>0){
            result.put(reqMap.get("number").toString(),addressList);
        }
        logAfter(logger);
        return new ResponseBean(Constants.CODE_SUCCESS,"操作成功",result);
    }

    @PostMapping(value="/getCity")
    public ResponseBean city(@RequestBody String str) {
        logBefore(logger, "查询市");
        Map<String, Object> result=new HashMap<>();
        Map<String, Object> reqMap = JSONObject.parseObject(str,Map.class);
        List<Map<String,Object>> addressList=appService.city(reqMap);
        if(null!=addressList&&addressList.size()>0){
            result.put(reqMap.get("number").toString(),addressList);
        }
        logAfter(logger);
        return new ResponseBean(Constants.CODE_SUCCESS,"操作成功",result);
    }

    @PostMapping(value="/getArea")
    public ResponseBean area(@RequestBody String str) {
        logBefore(logger, "查询区");
        Map<String, Object> result=new HashMap<>();
        Map<String, Object> reqMap = JSONObject.parseObject(str,Map.class);
        List<Map<String,Object>> addressList=appService.area(reqMap);
        addressList.forEach(item ->{
            item.put("isLeaf",true);
        });
        if(null!=addressList&&addressList.size()>0){
            result.put(reqMap.get("number").toString(),addressList);
        }
        logAfter(logger);
        return new ResponseBean(Constants.CODE_SUCCESS,"操作成功",result);
    }

    @PostMapping(value="/getRegionInfoList")
    public ResponseBean getRegionInfoList(HttpServletRequest request) throws MyException {
        logBefore(logger, "查询区域列表");
        Map<String, Object> reqMap = new HashMap<>();
        reqMap.put("sId", getCurrentUser(request).getS_id());
        List<Region> regionList = appService.getRegionIncludeProvinceAll(reqMap);
        logAfter(logger);
        return new ResponseBean(Constants.CODE_SUCCESS, "操作成功", regionList);
    }

    //民生银行需求,获取区域列表
    @PostMapping(value="/getRegionInfoListNew")
    public ResponseBean getRegionInfoListNew(HttpServletRequest request) throws MyException {
        logBefore(logger, "查询区域列表");
        Map<String, Object> reqMap = new HashMap<>();
        reqMap.put("sId", getCurrentUser(request).getS_id());
        List<Region> regionList = appService.getRegionIncludeProvinceAllNew(reqMap);
        List<Object> provinceList = new ArrayList<>();
        for(int i = 0; i < regionList.size(); i++) {
            List<Province> list = regionList.get(i).getChildren();
            for (int j = 0; j < list.size(); j++) {
                provinceList.add(list.get(j));
            }
        }
        logAfter(logger);
        return new ResponseBean(Constants.CODE_SUCCESS, "操作成功", provinceList);
    }

    //服务商销售可管辖区域列表(服务商管理区域 - 其他销售管理区域）
    @PostMapping(value="/getRegionInfoListSaleManagement")
    public ResponseBean getRegionInfoListSaleManagement(@RequestBody Map<String ,Object> param, HttpServletRequest request) throws MyException {
        logBefore(logger, "查询区域列表");
        Map<String, Object> reqMap = new HashMap<>();
        reqMap.put("sId", getCurrentUser(request).getS_id());
        reqMap.put("id", param.get("id"));
        List<Region> regionList = appService.getRegionIncludeProvinceSaleManagement(reqMap);
        List<Object> provinceList = new ArrayList<>();
        for(int i = 0; i < regionList.size(); i++) {
            List<Province> list = regionList.get(i).getChildren();
            for (int j = 0; j < list.size(); j++) {
                provinceList.add(list.get(j));
            }
        }
        logAfter(logger);
        return new ResponseBean(Constants.CODE_SUCCESS, "操作成功", provinceList);
    }

    //服务商销售可管辖区域列表(服务商管理区域 - 其他销售管理区域）
    @PostMapping(value="/getRegionInfoListSaleManagementForCarOwner")
    public ResponseBean getRegionInfoListSaleManagementForCarOwner(@RequestBody Map<String ,Object> param, HttpServletRequest request) throws MyException {
        logBefore(logger, "查询区域列表");
        Map<String, Object> reqMap = new HashMap<>();
        reqMap.put("sId", getCurrentUser(request).getS_id());
        reqMap.put("id", param.get("id"));
        List<Region> regionList = appService.getRegionIncludeProvinceSaleManagementForCarOwner(reqMap);
        logAfter(logger);
        return new ResponseBean(Constants.CODE_SUCCESS, "操作成功", regionList);
    }

    @PostMapping(value="/dataSupplement")
    public ResponseBean dataSupplement(HttpServletRequest request) throws MyException {
        new Thread(() -> {
            try {
                shangJiService.setLatitudeAndLongitudeForBuyInfo();
            } catch (MyException e) {
                e.printStackTrace();
            }
        }).start();
        new Thread(() -> {
            try {
                shangJiService.setLatitudeAndLongitudeForShopInfo();
            } catch (MyException e) {
                e.printStackTrace();
            }
        }).start();
        new Thread(() -> {
            try {
                // 设置维修店铺评价
                shangJiService.setEvaluationsForShopInfo();
            } catch (MyException e) {
                e.printStackTrace();
            }
        }).start();
        new Thread(() -> {
            try {
                // 职位类型随机处理
                shangJiService.setWorkTypeRandom();
            } catch (MyException e) {
                e.printStackTrace();
            }
        }).start();
        new Thread(() -> {
            try {
                // 租赁方式随机处理
                shangJiService.setRentalMethodForBuyInfoRandom();
            } catch (MyException e) {
                e.printStackTrace();
            }
        }).start();
        new Thread(() -> {
            try {
                // 工单逆地址坐标解析，通过坐标获取位置信息
                appService.regeo();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }).start();

        return new ResponseBean(Constants.CODE_SUCCESS, "操作成功", null);
    }

    /**
     * 获取服务商所能管辖的区域(省市县列表)
     * @param request
     * @return
     * @throws MyException
     */
    @PostMapping(value="/getRegionInfoListForServer")
    public ResponseBean getRegionInfoListForServer(HttpServletRequest request) throws MyException {
        logBefore(logger, "获取服务商所能管辖的区域");
        Map<String, Object> reqMap = new HashMap<>();
        reqMap.put("sId", getCurrentUser(request).getS_id());

        List<Region> regionList = appService.getRegionIncludeProvinceAll(reqMap); // 获取到未筛选的全部的大区及省市县列表
        List<Region> regionListForServer = new ArrayList<>(); // 筛选过的大区及省市县列表
        regionList.forEach(region -> {
            Region re = region;
            List<Province> proList = new ArrayList<>();
            re.getChildren().forEach(province -> {
                Province pro = province;
                List<City> cityList = new ArrayList<>();
                pro.getChildren().forEach(city -> {
                    City ci = city;
                    if (!ci.getDisabled()) {  // 不禁用的表示为当前服务商设置的城市
                        ci.setChildren(null); // 城市下面不显示区县
                        ci.setIsLeaf(true);   // 城市作为叶子节点，设置下面没有可以展开的节点
                        cityList.add(ci);
                    }
                });
                if (!pro.getDisabled()) { // 不禁用的表示为当前服务商设置的省份
                    pro.setChildren(cityList);
                    proList.add(pro);
                }
            });
            if(proList.size() > 0) {
                re.setExpanded(true);
                re.setChildren(proList);
                regionListForServer.add(re);
            }
        });

        logAfter(logger);
        return new ResponseBean(Constants.CODE_SUCCESS, "操作成功", regionListForServer);
    }
}
